package com.dstats.fragments;

import java.util.List;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ProgressBar;

import com.adapter.HeroAdapter;
import com.dstats.Constants;
import com.dstats.R;
import com.dstats.SimpleWebView;
import com.entities.Hero;
import com.fetch.FetchHeroes;

public class HeroesFragment extends Fragment {
	
	private GridView gridView;
	private ProgressBar pBar;
	private static FetchH fetchH;
	private void setAdapterAndListener(List<Hero> heroes) {
		if(heroes!=null){
			 gridView.setAdapter(new HeroAdapter(getActivity(), heroes));
	         gridView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> adapter, View arg1,
						int pos, long arg3) {
					Hero h = (Hero) adapter.getItemAtPosition(pos);
					/*
					Uri uri = Uri.parse(h.getHeropediaUrl());
					 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
					 startActivity(intent);*/

					Intent intent = new Intent(getActivity(), SimpleWebView.class);
					intent.putExtra("url", h.getHeropediaUrl());
					startActivity(intent);
					
				}
			});
		}
	}

	   public View onCreateView(LayoutInflater inflater, ViewGroup container,
	             Bundle savedInstanceState) {
	         View rootView = inflater.inflate(R.layout.hero_fragment, container, false);
	         gridView = (GridView) rootView.findViewById(R.id.gridViewHeroes);
	         pBar = (ProgressBar) rootView.findViewById(R.id.progressBarHeroesFragment);
	         setAdapterAndListener(Hero.heroes);
	         if(Hero.heroes==null){
	        	 if(fetchH==null){
	        		 fetchH = new FetchH(Constants.LANGUAGE);
	        		 fetchH.execute();
	        	 }
	         }
	        
	         return rootView;
	   }
	   
	   class FetchH extends FetchHeroes{

		public FetchH(String language) {
			super(language);
			}
		@Override
	    protected void onPreExecute() {
			pBar.setVisibility(View.VISIBLE);
			pBar.setIndeterminate(true);
	     
	    }
		@Override
	    protected void onPostExecute(final JSONObject result) {
			super.onPostExecute(result);
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					setAdapterAndListener(Hero.getHeroes(result));
					pBar.setVisibility(View.INVISIBLE);
				}


			});
			
	    }
	   }
	   
}
